import { ReactNode, FC, useState, useEffect, useCallback, useRef } from 'react';
import { memo } from 'react';
import Logout from '@/components/logout';
import { ChatContainerWrapper } from './style';
import ChatInput from './components/chatInput';
import { getAllMessage } from '@/store/chat/chatContainer';
import { saveMessage } from '@/store/chat/chatContainer/chatInput';
import { toast } from 'react-toastify';
import { BASE_URL } from '@/service/config';
import { message } from 'antd';

type IProps = {
  children?: ReactNode;
  currentChat: any;
  currentUser: any;
  socket: any;
  
};

const ChatContainer: FC<IProps> = ({ currentChat, currentUser, socket }) => {
  const [messages, setMessages] = useState<any[]>([]);
  const [arrivalMessage, setArrivalMessage] = useState<any>(null);
  const scrollRef = useRef<any>();

  const initMessages = useCallback(async () => {
    const messages = await getAllMessage(
      currentUser.username,
      currentChat.username,
    );
    setMessages(messages);
  }, [currentChat, currentUser]);

  const handleSendMessage = useCallback(
    async (currentMessage: string) => {
      const messageData = {
        message: currentMessage,
        receiver: currentChat.username,
        sender: currentUser.username,
        users: [currentUser.username, currentChat.username],
      };

      await saveMessage(messageData);
      socket.current?.send(JSON.stringify(messageData));
      // socket.current?.send('hi');
      const currentMessages = [...messages];
      currentMessages.push({ isSelf: true, message: currentMessage });
      setMessages(currentMessages);
    },
    [currentChat.username, currentUser.username, socket, messages],
  );

  const handleDeleteMessage = useCallback(
    async (messageContent: string) => {
      try {
        // 发送请求到后端删除消息
        const response = await fetch(`${BASE_URL}/deleteMessage`, {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json',
          },
          body: JSON.stringify({ messageContent }),
        });

        if (!response.ok) {
          toast.error('删除消息失败');
        }

        toast.success('删除消息成功');

        // 更新本地状态以移除消息
        setMessages((prevMessages) =>
          prevMessages.filter((message) => message.message !== messageContent),
        );
      } catch (error) {
        console.error('Error deleting message:', error);
      }
    },
    [setMessages],
  );

  const handleAddFriend = async () => {
    try {
      const response = await fetch(`${BASE_URL}/addFriendRelation`, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({
          senderId: currentUser.username,
          receiverId: currentChat.username,
        }),
      });
  
      const data = await response.json();
      if (response.ok) {
        if (data.message === 'Already friends') {
          toast.success('你们已经是好友了');
          return;
        }
        toast.success('添加好友成功');
      } else {
        toast.error(data.message);
      }
    } catch (error) {
      console.error('Add friend relationship', error);
      toast.error('添加好友失败, 请再试一次');
    }
  };

  useEffect(() => {
    initMessages();
  }, [initMessages]);

  useEffect(() => {
    if (socket.current) {
      socket.current.onmessage = (res: any) => {
        console.log(res.data, 'message');
        setArrivalMessage({ isSelf: false, message: res.data });
      };
    }
  }, [socket]);

  useEffect(() => {
    arrivalMessage && setMessages((prev) => [...prev, arrivalMessage]);
  }, [arrivalMessage]);

  useEffect(() => {
    scrollRef.current?.scrollIntoView({ behaviour: 'smooth' });
  }, [messages]);

  return (
    <>
      {currentChat && currentUser && (
        <ChatContainerWrapper>
          <div className="chat-header">
            <div className="user-details">
              <div className="avatar">
                <img src={currentChat.avatarImage} alt="avatar" />
              </div>
              <div className="username">
                <h3>{currentChat.username}</h3>
              </div>

              <button onClick={handleAddFriend}>Add Friend</button>
            </div>
            <Logout></Logout>
          </div>
          <div className="chat-messages">
            {messages.map((message, index) => {
              return (
                <div ref={scrollRef} key={message.id || index}>
                  <div
                    className={`message ${
                      message.isSelf ? 'sended' : 'received'
                    }`}
                    // 自己发的消息才可以被删除
                    onClick={() =>
                      message.isSelf && handleDeleteMessage(message.message)
                    }
                  >
                    <div className="content">
                      <p>{message.message}</p>
                    </div>
                  </div>
                </div>
              );
            })}
          </div>
          <ChatInput handleSendMessage={handleSendMessage}></ChatInput>
        </ChatContainerWrapper>
      )}
    </>
  );
};

export default memo(ChatContainer);
